package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IUserService userService;

    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //1.获取当前用户id
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;

        //判断是关注还是取关
        if(isFollow){
            //1.关注，新增
            Follow follow = new Follow();
            follow.setFollowUserId(followUserId);
            follow.setUserId(userId);
            boolean success = save(follow);
            if(success){
                //成功，以当前用户id为key，value用集合存关注的人

                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        }else {
            //2.取关  删除关注信息
            Boolean success = remove(new QueryWrapper<Follow>().eq("user_id",userId).eq("follow_user_id",followUserId));

            if(success) stringRedisTemplate.opsForSet().remove(key, followUserId);
        }

        return Result.ok();
    }

    @Override
    public Result isFollowed(Long followedUserId) {
        Long userId = UserHolder.getUser().getId();
        Integer count = query().eq("follow_user_id", followedUserId).eq("user_id", userId).count();
        return Result.ok(count > 0);
    }

    /**
     * 获取共同关注用户
     * @param otherUserId
     * @return
     */
    @Override
    public Result commonFollow(Long otherUserId) {
        Long userId = UserHolder.getUser().getId();

        String key1 = "follows:" + userId;
        String key2 = "follows:" + otherUserId;

        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key1, key2);

        if(intersect == null || intersect.isEmpty()) return Result.ok(Collections.emptyList());
        //解析交集结果ids
        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());

        //根据ids查询user
        List<User> users = userService.listByIds(ids);
        List<UserDTO> res = new ArrayList<>();
        for (User user : users) {
            UserDTO userDTO = new UserDTO();
            BeanUtil.copyProperties(user, userDTO);
            res.add(userDTO);
        }
        return Result.ok(res);
    }
}
